package org.example.oop.thread;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * org.example.oop.thread
 *
 * @author moLei
 * @description
 * @date 2025/6/25
 */
public class BlockQueueDemo {

    /**
     * 阻塞队列
     */
    private static final ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(10);

    public static void main(String[] args) {

        new Thread(() -> {
            while (true) {
                try {
                    // 队列中如果没有数据,take()方法会阻塞,直到有数据，take方法内部自带的有锁，不需要在外部手动加锁
                    String take = queue.take();
                    System.out.println(Thread.currentThread().getName() + "消费: " + take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "consumer-").start();


        new Thread(() -> {
            while (true) {
                try {
                    // 队列中如果没有空间,put()方法会阻塞,直到有空间，put方法内部自带的有锁，不需要在外部手动加锁
                    queue.put("hello");
                    System.out.println(Thread.currentThread().getName() + "生产: hello");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "producer-").start();
    }
}
